import { useEffect, useContext } from "react";
import { UserContext } from "../context/user/userContext";

export const AutoLogout = ({ brandCode, children }) => {  
  const {logout} = useContext(UserContext);
  let timer;
  const handleLogoutTimer = events => {
    timer = setTimeout(() => {
      resetTimer();
      Object.values(events).forEach((item) => {
        window.removeEventListener(item, resetTimer);
      });
      logoutAction();
    }, 900000);
  };

  const resetTimer = () => {
    if (timer) clearTimeout(timer);
  };

  useEffect(() => {
    const events = [
      "load",
      "mousemove",
      "mousedown",
      "click",
      "scroll",
      "keypress",
    ];
  
    const fn = () =>{
      Object.values(events).forEach((item) => {
        window.addEventListener(item, () => {
          resetTimer();
          handleLogoutTimer(events);
        });
      });
    }
    fn();    
  });

  const logoutAction = () => {
    logout();
  };

  return children;
};

export default AutoLogout;
